package store.lunangangster.bpmn.converter.parser;

import java.util.List;
import javax.xml.stream.XMLStreamReader;
import store.lunangangster.bpmn.constant.BpmnXmlConstant;
import store.lunangangster.bpmn.model.Process;
import store.lunangangster.bpmn.model.SubProcess;
import store.lunangangster.bpmn.model.Transaction;
import store.lunangangster.bpmn.util.BpmnXmlUtil;

public class SubProcessParser implements BpmnXmlConstant {

  public SubProcess parse(XMLStreamReader xsr, Process activeProcess, List<SubProcess> nestSubProcesses) {
    SubProcess subProcess;
    if (ELEMENT_TRANSACTION.equals(xsr.getLocalName())) {
     subProcess = new Transaction();
    } else {
     subProcess = new SubProcess();
    }

    BpmnXmlUtil.addXmlLocation(xsr, subProcess);

    String id = xsr.getAttributeValue(null, ATTRIBUTE_COMMON_ID);
    String name = xsr.getAttributeValue(null, ATTRIBUTE_COMMON_NAME);

    subProcess.setId(id);
    subProcess.setName(name);

    // exist parent SubProcess
    if (nestSubProcesses != null && nestSubProcesses.size() > 0) {
      SubProcess parentSubProcess = nestSubProcesses.get(nestSubProcesses.size() - 1);
      parentSubProcess.addFlowElement(subProcess);
    } else {
      activeProcess.addFlowElement(subProcess);
    }
    return subProcess;
  }
}
